<?php
/**
 * 客户端接口请求类
 *
 * 请妥善保存app_key和secret_key, 以免数据泄露
 *
 * @param string $app_key
 * @param string $secret_key
 */
namespace AuctionCore\Common;

use AuctionCore\Common\Xcrypt;
use AuctionCore\System\AuctionException;
use Think\Think;

class AntNest
{
	/**
	 * @var 预定义变量
	 */
	protected   $m;

	/**
	 * @var 车商类型
	 */
	protected   $account_type = '';

	/**
	 * @var 蚁巢请求地址
	 */
	protected   $ant_url = '';

	/**
	 * @var 项目唯一标识
	 */
//	private $_app_key =  'AK2016.API.1001';
	private $_app_key =  'AK2016.API.1003';
	/**
	 * @var 秘钥
	 */
	//private $_secret_key = 'ax1001erttt643ee';
	private $_secret_key = 'ax10ffer';
	private $_access_token = '';


	public function __construct(){
		$app_key    = C('APP_KEY');
		$secret_key = C('SECRET_KEY');
		if(!$app_key)    $app_key    = $this->_app_key;
		if(!$secret_key) $secret_key = $this->_secret_key;
		$m = new Xcrypt($secret_key, 'ecb', 'auto');
		$time_now = time();
		$access_key = $app_key . '_' . $secret_key . '_' . $time_now;
		$this->_app_key = $app_key;
		$this->_access_token = $m->encrypt($access_key, 'base64');

		$this->account_type = C('ACCOUNT_TYPE');
		$this->ant_url = C('ANT_URL');
	}

	/**
	 * 登录服务
	 * @param $city_code
	 */
	public function ant_login($userName='',$pwd=''){
		$option  = json_encode(array('account_type'=>$this->account_type,'user_name'=>$userName,'pwd'=>$pwd));
		$info = $this->juhecurl($this->ant_url.C('USE_ROUTE.login'),$option,1);
		$info = json_decode($info,true);
		if($info['code'] === "000000"){
			$result = array(
					'user_name'=>$info['data']['info']['account_name'],
					'uid'=>$info['data']['info']['account_id'],
					'pwd_mobile'=>$info['data']['info']['mobile'],
					'email'=>$info['data']['info']['email'],
					'status'=>$info['data']['info']['status'],
					'code'=>$info['code']
			);
			return $result;
		}else{
			return $info;
		}
	}


	/**
	 *  APP端临时使用方式  TODO 使用新版本后销毁
	 * @param string $user_name
	 * @return bool
	 * @throws AuctionException
	 */
	public function get_pwd($user_name=''){
		$option = json_encode(array('account_type'=>$this->account_type,'user_name'=>$user_name));
		$info   = $this->juhecurl($this->ant_url.C('USE_ROUTE.get_pwd'),$option);
		$info = json_decode($info,true);
		if($info['code'] === "000000"){
			return $info['data']['pwd'];
		}
		return '';
	}

	/**
	 * 根据uid获取用户信息
	 * @param string $uid 用户id
	 * @return array
	 * @throws AuctionException
	 */
	public  function  get_userinfo($uid = ''){
		$option  = json_encode(array('account_type'=>$this->account_type,'account_id'=>$uid));
		$info = $this->juhecurl($this->ant_url.C('USE_ROUTE.get_info_by_uid'),$option);
		$info = json_decode($info,true);
		if($info['code'] === "000000"){
			$result = array(
					'user_name'=>$info['data']['account_name'],
					'uid'=>$info['data']['account_id'],
					'pwd_mobile'=>$info['data']['mobile'],
					'nick_name'=>$info['data']['nick_name'],
					'real_name'=>$info['data']['real_name'],
					'avatar'=>$info['data']['account_avatar'],
					'createtime'=>$info['data']['reg_date'],
					'las_login_time'=>$info['data']['las_login_time'],
					'updatetime'=>$info['data']['last_modify_time'],
			);
			return $result;
		}
		return false;
	}

	/**
	 * 修改用户信息
	 * @param array $data   用户信息  account_id 必须
	 * @param string $error_msg   错误信息
	 * @return bool
	 * @throws AuctionException
	 */
	public  function set_user($data = array(),&$error_info=array()){
		if(!isset($data['account_id'])) {
            $error_info = array('code'=>'1000001','msg'=>AuctionException::$codes['1000001']);
            return false;
        }
		foreach($data as $key=>$val){
			$option[$key] = $val;
		}
		$option['account_type'] =$this->account_type;
		$info = $this->juhecurl($this->ant_url.C('USE_ROUTE.change_info'),json_encode($option),1);
		$info = json_decode($info,true);
		if($info['code'] === "000000"){
			return true;
		}else{
            $error_info = array('code'=>$info['code'],'msg'=>$info['msg']);
            \Think\Log::record('蚁巢错误码:'.$info['code']);
			return false;
		}
	}

	/**
	 * ant 车商注册
	 * @param array $option = array('account_name'=>用户名,'mobile'=>手机号码,'ver_code'=>验证码,'pwd'=>密码)
	 * @return mixed|string
	 * @throws AuctionException
	 */
	public function ant_regist($option = array()){
		$option['account_type'] =$this->account_type;
		$info = $this->juhecurl($this->ant_url.C('USE_ROUTE.regist'),json_encode($option),1);
		return json_decode($info,true);
	}

	/**验证手机号码是否被注册**/
	public function verify_mobile($option = array()){
		$option['account_type'] =$this->account_type;
		$info = $this->juhecurl($this->ant_url.C('USE_ROUTE.check_usr'),json_encode($option));
		return json_decode($info,true);
	}

	/**
	 * 找回密码
	 * @param array $option
	 * @return mixed
	 * @throws AuctionException
	 */
	public  function  retrieve_pwd($option = array()){
		$option['account_type'] =$this->account_type;
		$info = $this->juhecurl($this->ant_url.C('USE_ROUTE.retrieve_pwd'),json_encode($option),1);
		return json_decode($info,true);
	}
	/**
	 * 重置密码
	 * @param array $option
	 * @return mixed
	 * @throws AuctionException
	 */
	public  function  change_pwd($option = array()){
		$option['account_type'] =$this->account_type;
		$info = $this->juhecurl($this->ant_url.C('USE_ROUTE.change_pwd'),json_encode($option),1);
		return json_decode($info,true);
	}
	/***********************短信服务**********************/

	/**
	 * 获取短信验证码
	 * @param array $option = array('number'=>短信编号,'mobile'=>手机号码)
	 * @return bool
	 * @throws AuctionException
	 */
	public function get_sms($option = array()){
		$option['account_type'] =$this->account_type;
		$info = $this->juhecurl($this->ant_url.C('USE_ROUTE.sms'),json_encode($option),1);
		$info = json_decode($info,true);
		return $info;
	}

	/**
	 * @param array $option = array('number'=>短信编号,'mobile'=>手机号码,'ver_code'=>'验证码')
	 * @return bool
	 * @throws AuctionException
	 */
	public  function sms_verify($option = array(),&$error_msg=array()){
		$option['account_type'] =$this->account_type;
		$info = $this->juhecurl($this->ant_url.C('USE_ROUTE.sms_verify'),json_encode($option),1);
		$info = json_decode($info,true);
		if($info['code'] === "000000"){
			return true;
		}else{
            $error_msg = $info;
            trace('蚁巢错误码:'.var_export($info,true));
			return false;
		}
	}

	/************************RSA验证码服务***********************/
	/**
	 * 获取公钥、秘钥
	 * @return bool|mixed|string
	 * @throws AuctionException
	 */
	public function get_rsakey($type){
		$info = $this->juhecurl($this->ant_url.C('USE_ROUTE.get_rsa_key'),json_encode(array('key_type'=>$type)));
		$info = json_decode($info,true);
		if($info['code'] === "000000"){
			return $info;
		}
		return false;
	}

	/************************Jpush推送服务***********************/
	/**
	 * 向设备推送消息
	 * @return bool|mixed|string
	 * @throws AuctionException
	 */
	public function jpush($params){
		$params = json_encode($params);
		$res = $this->juhecurl($this->ant_url.C('USE_ROUTE.jpush'), $params, 1);
		$info = json_decode($res,true);
		if($info['code'] === "000000"){
			return $info;
		}
		return false;
	}

	/**
	 * 请求接口返回内容
	 *
	 * @param  string $url [请求的URL地址]
	 * @param  string $header [header权限校验参数]
	 * @param  json $params [请求的参数]
	 * @param  int $ipost [是否采用POST形式]
	 * @return  string
	 */
	public function juhecurl($url, $params='', $ispost=0){
		$httpInfo = array();
		$ch = curl_init();
		$header = array(
				"content-type: application/x-www-form-urlencoded; charset=UTF-8",
				'appkey:' . $this->_app_key,
				'token:' . $this->_access_token,
		);
		curl_setopt($ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
		curl_setopt($ch,CURLOPT_USERAGENT,"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)");
		curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 30 );
		curl_setopt( $ch, CURLOPT_TIMEOUT , 30);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER , true );
		curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
		curl_setopt ($ch, CURLOPT_COOKIE, 'XDEBUG_SESSION=1');
        if (ini_get('open_basedir') == '' && ini_get('safe_mode' == 'Off')) {
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        }

		$params = json_decode($params, true);
		$data = http_build_query($params);
		/*备注： 如果后期需要对http通讯过程中的数据做加密传输，则打开以下代码*/
		// $m = new \Common\Org\Xcrypt($key, 'ecb', 'auto');
		// $data = $m->encrypt($a);
		if( $ispost )
		{
			curl_setopt( $ch , CURLOPT_POST , true );
			curl_setopt( $ch , CURLOPT_POSTFIELDS , $data );
			curl_setopt( $ch , CURLOPT_URL , $url );
		}
		else
		{
			$strUrl = !empty($data) ? $url.'?'.$data : $url;
			curl_setopt( $ch , CURLOPT_URL , $strUrl);
		}
		$response = curl_exec( $ch );
		$error = curl_error($response);
		if ($response === FALSE) {
			throw new AuctionException("AN接口访问异常！");
		}
		$httpCode = curl_getinfo( $ch , CURLINFO_HTTP_CODE );
		$httpInfo = array_merge( $httpInfo , curl_getinfo( $ch ) );
		curl_close( $ch );
		$is_json = self::isJson($response);
		$result = json_decode($response,true);
		if(!$is_json || empty($result['code'])){
			return json_encode(array('code'=>"009453",'msg'=>'系统异常'));
		}
		return $response;
	}

	/**
	 * 判断是否为json
	 * @param string $string
	 * @return bool
	 */
	private static function isJson($string = ''){
		json_decode($string);
		return (json_last_error() == JSON_ERROR_NONE);
	}
    /**
     * 获取支付签名
     *
     * @param $mapOrderNo
     * @param $orderTitle
     * @param $totalAmount
     * @param $mapNoticeUrl
     * @param $mapCallBackUrl
     *
     * @return bool
     */
    public function generate($option = array())
    {
        $params = json_encode($option);
        $res = $this->juhecurl($this->ant_url.C('USE_ROUTE.rpc_pay'),$params,1);
        $info = json_decode($res,true);
        if($info['code'] === "000000"){
            return $info;
        }else{
            trace('蚁巢错误码:'.var_export($info,true),'','ERR',true);
            return false;
        }
    }
	/**
	 * 同步支付结果校验
	 *
	 * @param $channel
	 * @param $tradePayResponse
	 */
	public function verify($channel, $tradePayResponse)
	{
		$param = array(
			'channel' => $channel,
			'trade_area' => 'zb',
			'trade_pay_response' => urlencode($tradePayResponse)
		);
        $params = json_encode($param);
        $res = $this->juhecurl($this->ant_url.C('USE_ROUTE.verify'),$params,1);
        $info = json_decode($res,true);
        if($info['code'] === "000000"){
            return $info;
        }else{
            $error_msg = $info;
            trace('蚁巢错误码:'.var_export($error_msg,true));
            return false;
        }
	}
	/**
	 * 按支付订单查询订单交易状态
	 *
	 * @param $payNo
	 *
	 * @return bool
	 */
	public function searchByBill($option = array())
	{
		$params = json_encode($option);
		$this->urlPath = C('RPC_PAY_TRADE') . 'searchbybill';
		$res = $this->juhecurl($this->ant_url.C('USE_ROUTE.searchbybill'),$params,1);
		$info = json_decode($res,true);
		if($res['code'] === "000000"){
			return $info;
		}else{
			$error_msg = $info;
			trace('蚁巢错误码:'.var_export($error_msg,true));
			return false;
		}
	}
	/*********维保查询***********/
	/**
	 * VIN码查询接口
	 * @param array $option = array('vin'=>LGBG12E047Y572211,'callbackurl'=>xxxxx,'engineno'=>xxx,'licenseplate'=>xxx)
	 * @return array
	 * @throws AuctionException
	 */
	public function getRepairReport($option = array()){
		$params = json_encode($option);
		$res = $this->juhecurl($this->ant_url.C('USE_ROUTE.repair_report'), $params, 1);
		$info = json_decode($res,true);
		if($info['code'] === "000000"){
			return $info;
		} else if($info['code'] === "900024") {
			return $info;
		} else {
			trace('蚁巢错误码:'.var_export($info,true),'','ERR',true);
			return false;
		}
	}
	/**
	 * 维保报告详情查询接口
	 * @param array $option = array('rid'=>518)
	 * @return array
	 * @throws AuctionException
	 */
	public function getRepairDetail($option = array()){
		$params = json_encode($option);
		$res = $this->juhecurl($this->ant_url.C('USE_ROUTE.report_detail'), $params, 1);
		$info = json_decode($res,true);
		if($info['code'] === "000000"){
			return $info['data'];
		}else{
			trace('蚁巢错误码:'.var_export($info,true),'','ERR',true);
			return false;
		}
	}
}